package com.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.springboot.config.ConsumerConfig;
import com.springboot.db.entity.User;
import com.springboot.dubbo.consumer.UserConsumer;
import com.springboot.mongo.service.UserLoginService;
import com.springboot.redis.RedisUtil;
import com.springboot.service.UserService;
import com.springboot.zookeeper.ZookeeperConfigService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.log4j.Log4j2;
import org.I0Itec.zkclient.ZkClient;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试controller
 *
 * @author supu
 * @create 2018-12-12 13:34
 **/
@Log4j2
@RestController
public class TestController {
    
    /**
     * {@link UserService#selectUsers()}
     */
    @Autowired
    private UserService userService;
    @Autowired
    private Environment environment;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ZookeeperConfigService zookeeperConfigService;
    @Autowired
    private ZkClient zkClient;
    @Autowired
    private UserConsumer userConsumer;
    @Autowired
    private ConsumerConfig consumerConfig;
    @Autowired
    private CuratorFramework curatorFramework;
    @Autowired
    private UserLoginService userLoginService;

    @GetMapping("/index")
    public void index(){
        log.info(JSONObject.toJSONString(userService.selectUsers()));
    }

    @GetMapping("/selectUser")
    @ResponseBody
    public String selectUser(Integer id){
        return JSONObject.toJSONString(userService.selectUserById(id));
    }

    @GetMapping("/redis")
    @ResponseBody
    public String redisTest(){


        List<User> users = userService.selectUsers();

        redisUtil.setValue("users", users, 5 * 60);

        List<User> cacheUsers = (List<User>)redisUtil.getValue("users");
        log.error(JSONObject.toJSONString(cacheUsers));

        Map<String, Object> map = new HashMap<>(2);
        users.forEach(user -> {
            map.put(user.getName(), user);
        });
        redisUtil.setValue("map", map, 5 * 60);

        Map<String, Object> cacheMap = (Map<String, Object>)redisUtil.getValue("map");
        log.warn(JSONObject.toJSONString(cacheMap));
        log.warn(cacheMap.get("zs"));

        return "redis test";
    }

    @GetMapping("/zk")
    @ResponseBody
    public String zkTest(String node){
       String watchNodePath = environment.getProperty("zookeeper.watch.node");

       if(!zkClient.exists(watchNodePath)){
           zkClient.createPersistent(watchNodePath, true);
       }

       zkClient.createEphemeral(watchNodePath+"/"+node, node);

        return "zk test";
    }

    @GetMapping("/dubbo")
    @ResponseBody
    public String dubboTest(Integer id){
        return JSONObject.toJSONString(userConsumer.getUsers(id));
    }

    @GetMapping("/dubboSave")
    @ResponseBody
    public String dubboSaveTest(){
        userConsumer.saveUser();
        return "dubboSave test";
    }

    @GetMapping("/curator/test")
    @ResponseBody
    public String curatorTest(Integer type, String path, String value){
        String rootPath = consumerConfig.getString(ConsumerConfig.ZOOKEEPER_GROUP);
        path = rootPath + "/" + path;
        if(type == 1){
            // 新增节点
            try {
                curatorFramework.create().creatingParentContainersIfNeeded().forPath(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if(type == 2){
            // 新增节点及其数据
            try {
                curatorFramework.create().creatingParentContainersIfNeeded().forPath(path, value.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(type == 3){
            // 更新节点及其数据
            try {
                curatorFramework.setData().forPath(path, value.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if(type == 4) {
            // 删除节点
            try {
                curatorFramework.delete().deletingChildrenIfNeeded().forPath(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return "curator operator test";
    }

    @GetMapping("/mongo/query")
    @ResponseBody
    public Object mongoQuery(String userName){
        return userLoginService.queryUserLoginList(userName);
    }

    @GetMapping("/mongo/update")
    @ResponseBody
    public Object mongoUpdate(String userName){
        userLoginService.updateUserLogin(userName);
        return "success";
    }

    @GetMapping("/distributed/updateTest")
    @ResponseBody
    public Object distributedUpdateTest(Integer id, boolean isRollback1, boolean isRollback2){
        userService.updateUser(id,isRollback1,isRollback2);
        return "success";
    }

    @GetMapping("/distributed/saveTest")
    @ResponseBody
    public Object distributedSaveTest(Integer id, boolean isRollback1, boolean isRollback2){
        userService.saveUser(id,isRollback1,isRollback2);
        return "success";
    }
}
